﻿using System;
using System.IO;
using System.Net;
using System.Threading;

namespace XamlTorrent.Managers.UriGetter.Downloaders
{
    class DefaultDownloader : DownloaderBase
    {
        public DefaultDownloader(Uri source, FileInfo fileInfo) : base(source, fileInfo) { }

        protected override ContentHeaderData GetHeaderData()
        {
            WebRequest webReq = WebRequest.Create(base.Source);

            WebResponse webResp = webReq.GetResponse();
            
            ContentHeaderData header = new ContentHeaderData(webResp.ContentLength, null);

            return header;
        }

        protected override long DownloadSegment(FileSegment segment)
        {
            WebRequest webReq = WebRequest.Create(base.Source);

            System.Diagnostics.Debug.WriteLine("Thread" + Thread.CurrentThread.ManagedThreadId + ": making request.");

            using (WebResponse webResp = (WebResponse)webReq.GetResponse())
            {
                System.Diagnostics.Debug.WriteLine("Thread" + Thread.CurrentThread.ManagedThreadId + ": got response.");

                Stream dataStream = webResp.GetResponseStream();

                System.Diagnostics.Debug.WriteLine("Thread" + Thread.CurrentThread.ManagedThreadId + ": reading data.");

                byte[] buffer = new byte[8192];
                long total = 0;
                int count;

                while ((count = dataStream.Read(buffer, 0, buffer.Length)) > 0 && !segment.IsFull)
                {
                    segment.Write(buffer, 0, count);
                    total += count;
                }

                webResp.Close();

                System.Diagnostics.Debug.WriteLine("Thread" + Thread.CurrentThread.ManagedThreadId + ": finished " + total + " bytes.");

                return total;
            }
        }
    }
}
